package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2024-01-27
 * Time: 15:24
 */
//Socket:套接字，用于网络编程的kpi
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int port;
    public UdpEchoClient(String serverIp,int port) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.port = port;
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("-> ");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),port);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("req:%s, res:%s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
